#!/bin/bash

#
# (c) 2009 Mandriva, http://www.mandriva.com/
# (c) 2009 Jean-Dominique Frattini, jd.frattini@free.fr
#
# $Id: $
#
# This file is part of ATS (Automated Testing System), 
# http://http://wiki.mandriva.com/en/Automated_testing_system
#
# ATS is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# ATS is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Pulse 2; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.

# usage: timered-sh.sh <TIMELIMIT> <COMMAND>

KILL_CMD=`which kill`
STTY_CMD=`which stty`
TIME_LIMIT=$1
CMD=$2
TIMER_PID=0
CMD_PID=0
USAGE="timered-sh.sh <TIMELIMIT> <COMMAND>"

# saving tty settings
# could be well but provokes some badnesses depending on how the binary behaves
#TTY_SETTINGS=`$STTY_CMD -g`

TimerOn()
{
   sleep ${TIME_LIMIT} && ${KILL_CMD} -s SIGALRM $$ &
   TIMER_PID=$!
}

Int14Vector()
{
   echo "${CMD} has timed out !" >&2
   ${KILL_CMD} -TERM ${CMD_PID}
   exit 14
}

if [ $# -ne 2 ]
then
   echo "Usage: ${USAGE}"
   exit 1
fi

trap Int14Vector SIGALRM

echo "Running ${CMD} with ${TIME_LIMIT} seconds limitation"
TimerOn
${CMD} &
CMD_PID=$!
echo "Waiting for ${CMD}..."
wait ${CMD_PID}
echo "Ended."
#read answer # just for testing purposes
echo "${CMD} has finished before timeout"
kill ${TIMER_PID}

# taking back tty setting (see above)
#$STTY_CMD "$TTY_SETTINGS"

exit 0
